Page({
  data: {},
  onLoad: function (options) {
    this.setData({
      goBack: Number(options.goBack)
    });
  },
  onShow: function () {
    this.setData({
      pageIndex: 1,
      invoiceList: [],
      noMore: false
    }, () => {
      this.getInvoice();
    });
  },
  onReachBottom: function () {
    if (this.data.noMore) return;
    this.getInvoice();
  },
  getInvoice: function () {
    let page = this.data.pageIndex;
    wx.util.request('', {
      body: {page: page}
    }).then(res => {
      this.setData({
        pageIndex: page + 1,
        invoiceList: this.data.invoiceList.concat(res),
        noMore: res.length < 10
      });
    }).catch(err => {
      console.log(err)
    });
  },
  edit: async function (e) {
    let address = this.data.invoiceList[e.currentTarget.dataset.index];
    wx.navigateTo({
      url: `edit?id=${(address && address.id) || ''}&delta=${(this.data.goBack || 0) + 1}` 
    });
  },
  default: function (e) {
    let index = e.currentTarget.dataset.index,
        list = this.data.invoiceList,
        invoice = list[index];
    if (invoice.is_default == 1) return;
    wx.util.request('invoice.modify', {
      query: `id=${invoice.id}`,
      body: {
        type: invoice.type,
        title: invoice.title,
        is_default: 1
      }
    }).then(() => {
      // 更新列表数据
      for (let i in list) {
        list[i].is_default = 0;
        if (i == index) list[i].is_default = 1;
      }
      this.setData({
        invoiceList: list
      });
      if (this.data.goBack === 1) wx.navigateBack();
    });
  }
})

// 如果没有设置过发票，可授权调用wx.chooseInvoice获得微信发票